import React, { useState, memo } from 'react';
import { Avatar, Dropdown, Typography, message as antMessage, Drawer, List } from 'antd';
import {
  UserOutlined,
  RobotOutlined,
  CopyOutlined,
  EditOutlined,
  ReloadOutlined,
  DeleteOutlined,
  MoreOutlined
} from '@ant-design/icons';
import TypewriterEffect from '../../TypewriterEffect';
import MarkdownRenderer from '../MarkdownRenderer';
import { Message } from '../../../stores/conversation.store';
import { useConversationStore } from '../../../stores/conversation.store';
import { useBreakpoint } from '../../../hooks/useBreakpoint';
import { useLongPress } from '../../../hooks/useLongPress';
import './style.css';

const { Text } = Typography;

interface MessageBubbleProps {
  message: Message;
}

const MessageBubble: React.FC<MessageBubbleProps> = memo(({ message }) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  const [isEditing, setIsEditing] = useState(false);
  const [editContent, setEditContent] = useState(message.content);
  const [showMobileMenu, setShowMobileMenu] = useState(false);
  const { updateMessage, deleteMessage, regenerateMessage, settings } = useConversationStore();

  const handleCopy = () => {
    navigator.clipboard.writeText(message.content);
    antMessage.success('已复制到剪贴板');
    setShowMobileMenu(false);
  };

  const handleEdit = () => {
    setIsEditing(true);
    setEditContent(message.content);
    setShowMobileMenu(false);
  };

  const handleSaveEdit = () => {
    updateMessage(message.id, editContent);
    setIsEditing(false);
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditContent(message.content);
  };

  const handleDelete = () => {
    deleteMessage(message.id);
    setShowMobileMenu(false);
  };

  const handleRegenerate = () => {
    if (message.role === 'assistant') {
      regenerateMessage(message.id);
    }
    setShowMobileMenu(false);
  };

  // 长按触发移动端菜单
  const longPressHandlers = useLongPress({
    onLongPress: () => {
      if (isMobile) {
        setShowMobileMenu(true);
      }
    },
    delay: 500,
  });

  const menuItems = [
    {
      key: 'copy',
      label: '复制',
      icon: <CopyOutlined />,
      onClick: handleCopy,
    },
    {
      key: 'edit',
      label: '编辑',
      icon: <EditOutlined />,
      onClick: handleEdit,
    },
    ...(message.role === 'assistant'
      ? [
          {
            key: 'regenerate',
            label: '重新生成',
            icon: <ReloadOutlined />,
            onClick: handleRegenerate,
          },
        ]
      : []),
    {
      type: 'divider',
    },
    {
      key: 'delete',
      label: '删除',
      icon: <DeleteOutlined />,
      onClick: handleDelete,
      danger: true,
    },
  ];

  const isUser = message.role === 'user';

  return (
    <>
      <div
        className={`message-bubble-wrapper ${isUser ? 'user' : 'assistant'}`}
        {...(isMobile ? longPressHandlers : {})}
      >
        <div className="message-bubble-avatar">
          <Avatar
            size={isMobile ? 32 : 40}
            icon={isUser ? <UserOutlined /> : <RobotOutlined />}
            style={{
              backgroundColor: isUser ? '#1890ff' : '#52c41a',
            }}
          />
        </div>

        <div className="message-bubble-content-wrapper">
          <div className="message-bubble-header">
            <Text className="message-bubble-name">
              {isUser ? '你' : 'AI 助手'}
            </Text>
            {settings.showTimestamp && (
              <Text
                className="message-bubble-time"
                type="secondary"
                style={{ fontSize: isMobile ? '10px' : '12px' }}
              >
                {new Date(message.timestamp).toLocaleTimeString()}
              </Text>
            )}
          </div>

          <div className={`message-bubble-body ${isMobile ? 'mobile' : ''}`}>
            {isEditing ? (
              <div className="message-edit-area">
                <textarea
                  className="message-edit-input"
                  value={editContent}
                  onChange={(e) => setEditContent(e.target.value)}
                  autoFocus
                />
                <div className="message-edit-actions">
                  <button onClick={handleSaveEdit} className="btn-save">
                    保存
                  </button>
                  <button onClick={handleCancelEdit} className="btn-cancel">
                    取消
                  </button>
                </div>
              </div>
            ) : (
              <>
                {message.status === 'streaming' && !isUser ? (
                  <TypewriterEffect
                    text={message.content}
                    speed={30}
                    showCursor={true}
                    renderMarkdown={settings.enableMarkdown}
                    autoStart={true}
                  />
                ) : settings.enableMarkdown ? (
                  <MarkdownRenderer content={message.content} />
                ) : (
                  <div className="message-plain-text">{message.content}</div>
                )}
              </>
            )}
          </div>

          {/* 桌面端：悬浮菜单按钮 */}
          {!isMobile && (
            <div className="message-bubble-actions">
              <Dropdown
                menu={{ items: menuItems }}
                trigger={['click']}
                placement="bottomRight"
              >
                <button className="message-action-button">
                  <MoreOutlined />
                </button>
              </Dropdown>
            </div>
          )}
        </div>
      </div>

      {/* 移动端：底部抽屉菜单 */}
      {isMobile && (
        <Drawer
          placement="bottom"
          open={showMobileMenu}
          onClose={() => setShowMobileMenu(false)}
          height="auto"
          closable={false}
          styles={{ body: { padding: 0 } }}
        >
          <List
            dataSource={menuItems.filter(item => item.type !== 'divider')}
            renderItem={(item: any) => (
              <List.Item
                onClick={item.onClick}
                className={`mobile-menu-item ${item.danger ? 'danger' : ''}`}
                style={{
                  minHeight: '56px',
                  cursor: 'pointer',
                  padding: '16px 24px'
                }}
              >
                <List.Item.Meta
                  avatar={item.icon}
                  title={
                    <span style={{
                      fontSize: '16px',
                      color: item.danger ? '#ff4d4f' : undefined
                    }}>
                      {item.label}
                    </span>
                  }
                />
              </List.Item>
            )}
          />
        </Drawer>
      )}
    </>
  );
});

MessageBubble.displayName = 'MessageBubble';

export default MessageBubble;